// 运行时配置
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate

import { queryCurrentUser } from '@/services/demo/UserController';
import { history, RequestConfig, RunTimeLayoutConfig } from '@umijs/max';

import {
  AvatarDropdown,
  AvatarName,
} from '@/components/RightContent/AvatarDropdown';

const loginPath = '/user/login';
export async function getInitialState(): Promise<{
  name: string;
  currentUser?: API.CurrentUser;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser({
        skipErrorHandler: true,
      });
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  const { location } = history;
  if (
    ![loginPath, '/user/register', '/user/register-result'].includes(
      location.pathname,
    )
  ) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      name: '@umijs/max',
    };
  }
  return {
    fetchUserInfo,
    name: '@umijs/max',
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
    layout: 'mix',
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
  };
};

export const request: RequestConfig = {
  timeout: 1000,
  // other axios options you want
  errorConfig: {
    errorHandler() {},
    errorThrower() {},
  },
  requestInterceptors: [
    (config: any) => {
      let token = localStorage.getItem('token') || '';
      return {
        ...config,
        headers: {
          ...config.headers,
          authorization: token,
        },
      };
    },
  ],
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      const headers = response.headers;
      // 设置token
      if (headers.authorization) {
        localStorage.setItem('token', headers.authorization);
      }
      return response;
    },
  ],
};
